//
//  AuthLoginViewModel.m
//  MobileChecker
//
//  Created by Lymons on 15-1-5.
//  Copyright (c) 2015年 Lymons. All rights reserved.
//

#import "AuthLoginViewModel.h"
#import "UIDevice+IdentifierAddition.h"
#import "CheckResultUserDefaults.h"

@implementation AuthLoginViewModel

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (AuthLoginService *)service
{
    if (_service == nil) {
        _service = [[AuthLoginService alloc] init];
    }
    return _service;
}

- (void)initialize {
    
    RACSignal *validAuthCodeSignal =
    [[RACObserve(self, authCode)
      map:^id(NSString *text) {
          return @(text.length > 3);
      }]
     distinctUntilChanged];
    
    [validAuthCodeSignal subscribeNext:^(id x) {
        NSLog(@"search text is valid %@", x);
    }];
    
    self.executeAuth =
    [[RACCommand alloc] initWithEnabled:validAuthCodeSignal
                            signalBlock:^RACSignal *(id input) {
                                return  [self executeAuthSignal];
                            }];
    self.executeSend =
    [[RACCommand alloc] initWithEnabled:validAuthCodeSignal
                            signalBlock:^RACSignal *(id input) {
                                return  [self executeSendResultSignal];
                            }];
    
//    self.connectionErrors = self.executeAuth.errors;
    self.connectionErrors = [RACSignal merge:@[self.executeAuth.errors, self.executeSend.errors]];
}

- (RACSignal *)executeAuthSignal {
    [CheckResultUserDefaults standardUserDefaults].authCode = self.authCode;
    
    return [[self.service authLoginSignal:self.authCode]
            doNext:^(id result) {
                // results;
                if ([result isKindOfClass:[NSDictionary class]]) {
                    BOOL fpn = [[result objectForKey:RESP_KEY_COMPANYID] isEqualToString:RESP_VLU_COMPANYID];
                    [CheckResultUserDefaults standardUserDefaults].shouldShowIMEIButton = fpn;
                    BOOL asse = ([[result objectForKey:RESP_KEY_ASSE] intValue] == 1 && fpn);
                    [CheckResultUserDefaults standardUserDefaults].shouldShowPriceButton = asse;
                }
                self.apiSucceed = YES; // must be last
            }];
}

- (RACSignal *)executeSendResultSignal {
    UIDevice *dev = [UIDevice currentDevice];
    CheckResultUserDefaults *defaults = [CheckResultUserDefaults standardUserDefaults];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    params[KEY_AUTHID] = defaults.authCode;
    params[KEY_SHOPCD] = self.authCode;
    NSString *imei = dev.serialNumber;
    if (imei) {
        params[KEY_IMEI] = imei;
    }
    imei = defaults.shouldShowIMEIButton ? defaults.imeiCodeString : nil;
    if (imei) {
        params[KEY_IMEI_INPUT] = imei;
    }
    params[KEY_CAREER] = dev.carrierName;
    params[KEY_MAKER] = @"APPLE";
    params[KEY_MODEL] = dev.model;
    params[KEY_MODEL_NAME] = dev.machineShortName;
    params[KEY_VOLUME] = DEVICE_TOTAL_VOLUME;
    params[KEY_OS] = dev.systemVersion;
    params[KEY_SENSOR] = [CheckResultUserDefaults sensorResultAPIString];
    NSString *compa = [CheckResultUserDefaults resultAPIString:defaults.compassCheckResult];
    NSString *magne = [CheckResultUserDefaults resultAPIString:defaults.magneticCheckResult];
    NSString *proxi = [CheckResultUserDefaults resultAPIString:defaults.proximityCheckResult];
    NSString *lumin = [CheckResultUserDefaults resultAPIString:defaults.luminaCheckResult];
    params[KEY_SENSOR_DETAILS] = VALUE_SENSOR(compa, magne, proxi, lumin);
    params[KEY_COMMUNICATION] = [CheckResultUserDefaults communicationResultAPIString];
    NSString *wifi = [CheckResultUserDefaults resultAPIString:defaults.wifi3gCheckResult];
    NSString *blue = [CheckResultUserDefaults resultAPIString:defaults.bluetoothCheckResult];
    params[KEY_COMMUNICATION_DETAILS] = VALUE_COMMUNICATION(wifi, blue);
    params[KEY_TOUCH_PANEL] = [CheckResultUserDefaults resultAPIString:defaults.touchCheckResult];
    params[KEY_VIBRATION] = [CheckResultUserDefaults resultAPIString:defaults.vibrationCheckResult];
    params[KEY_SPEAKER] = [CheckResultUserDefaults resultAPIString:defaults.soundCheckResult];
    params[KEY_MIKE] = [CheckResultUserDefaults resultAPIString:defaults.recordCheckResult];
    params[KEY_CAMERA] = [CheckResultUserDefaults resultAPIString:defaults.cameraCheckResult];
    params[KEY_LIQUID_CRYSTAL] = [CheckResultUserDefaults resultAPIString:defaults.screenCheckResult];
    params[KEY_BATTERY] = [CheckResultUserDefaults resultAPIString:defaults.batteryCheckResult];
    params[KEY_SIM] = [CheckResultUserDefaults resultAPIStringForSim:defaults.simCardCheckResult];
    params[KEY_DIAGNOSTICS_RESULT] = [CheckResultUserDefaults diagnosisResultAPIString];
    
    NSString *File = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:File];
    params[KEY_VERSION] = [dict objectForKey:@"App version"];
    
//    NSDictionary *entity = @{KEY_ROOT : params};
//    return [[self.service sendResultSignal:entity]
    return [[self.service sendResultSignal:params]
            doNext:^(NSDictionary *result) {
                // results;
                self.assessmentNoString = result[KEY_ASSESSMENT];
                self.successMessageString = result[KEY_SUCCEEDMESSAGE];
                self.apiSucceed = YES; // must be last
            }];
}

@end
